package com.zzhrtech.wgzx_cityzen.ui.contact;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.GsonRequest;
import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.zzhrtech.WgzxApplication;
import com.zzhrtech.wgzx_cityzen.Constans;
import com.zzhrtech.wgzx_cityzen.MainActivity;
import com.zzhrtech.wgzx_cityzen.R;
import com.zzhrtech.wgzx_cityzen.adapters.contact.NormalRecyclerViewAdapter;
import com.zzhrtech.wgzx_cityzen.base.BaseFragment;
import com.zzhrtech.wgzx_cityzen.base.OnItemClickLitener;
import com.zzhrtech.wgzx_cityzen.beans.contact.ActivListBean;
import com.zzhrtech.wgzx_cityzen.ui.me.MyInfoActivity;
import com.zzhrtech.wgzx_cityzen.ui.me.WebviewActivity;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zzhrtech.wgzx_cityzen.Constans.HTTP_JFGZ;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ActivFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ActivFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private RecyclerView rc_activ;
    private SwipeToLoadLayout swipeToLoadLayout;
    private NormalRecyclerViewAdapter activAdapter;

    List<ActivListBean.Data> datas;
    public int screenWidth;


    public ActivFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment ActivFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ActivFragment newInstance() {
        ActivFragment fragment = new ActivFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        setHasOptionsMenu(true);
    }


    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_activ, container, false);
        rc_activ = (RecyclerView) view.findViewById(R.id.swipe_target);
        swipeToLoadLayout = (SwipeToLoadLayout) view.findViewById(R.id.swipeToLoadLayout);
        rc_activ.setLayoutManager(new LinearLayoutManager(mActivity));
        rc_activ.setItemAnimator(new DefaultItemAnimator());
        activAdapter = new NormalRecyclerViewAdapter(mActivity);
        rc_activ.setAdapter(activAdapter);

        activAdapter.setOnItemClickLitener(new OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                if (!datas.get(position).getIsend()) {

                    if (datas.get(position).getType().equals("3")) {
//                        if (datas.get(position).getCanplay()) {
                            Intent intent = new Intent(mActivity, GoodsActivity.class);
                            intent.putExtra("activid", datas.get(position).getId());
                            startActivityForResult(intent,2);
//                        }
                    } else {
                        Intent intent = new Intent(mActivity, WebviewActivity.class);
                        intent.putExtra("url", datas.get(position).getPlay());
                        intent.putExtra("title", "抽奖");
                        startActivity(intent);
                    }
                }
            }
        });

        DisplayMetrics metric = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        screenWidth = metric.widthPixels;

        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);
        return view;
    }

    @Override
    protected void initData() {
        super.initData();

        swipeToLoadLayout.setRefreshing(true);
    }



    private void httpGetActiv(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("citizen_id",((MainActivity) mActivity).getCache().getAsString(Constans.keyUid));

        GsonRequest<ActivListBean> gsonRequest = new GsonRequest<ActivListBean>(Request.Method.POST, Constans.HTTP_ACTIVLIST, ActivListBean.class, params, new com.android.volley.Response.Listener<ActivListBean>() {
            @Override
            public void onResponse(ActivListBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 1;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {
                    showToast(response.getMsg());
                    swipeToLoadLayout.setRefreshing(false);
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
                swipeToLoadLayout.setRefreshing(false);
//                dialog.dismiss();
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            if (msg.what == 1) {

                swipeToLoadLayout.setRefreshing(false);

                datas = (List<ActivListBean.Data>) msg.obj;

                for (ActivListBean.Data data : datas){
                    //只显示兑换
//                    if (data.getType().equals("3"))
                    activAdapter.addItem(data);
                }
            }

            return false;
        }
    });


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

        inflater.inflate(R.menu.menu_activ, menu);

        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.upload){
            Intent intent = new Intent(mActivity,WebviewActivity.class);
            intent.putExtra("title","积分规则");
            intent.putExtra("url",HTTP_JFGZ);
            startActivity(intent);
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 2 & resultCode == Activity.RESULT_OK){

            swipeToLoadLayout.setRefreshing(true);

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (swipeToLoadLayout.isRefreshing()) {
            swipeToLoadLayout.setRefreshing(false);
        }
        if (swipeToLoadLayout.isLoadingMore()) {
            swipeToLoadLayout.setLoadingMore(false);
        }
    }

    @Override
    public void onRefresh() {
        activAdapter.cleanList();
        httpGetActiv();
    }

    @Override
    public void onLoadMore() {
        swipeToLoadLayout.setLoadingMore(false);
    }
}
